import axios from 'axios';
import { Message } from 'ant-design-vue';
import store from '@/store';

const instance = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 20000,
  withCredentials: true
});

instance.interceptors.request.use(config => {
  return config;
}, err => {
  return Promise.reject(err);
});

instance.interceptors.response.use(response => {
  const { code } = response.data;

  if (code >= 200 && code < 300) {
    // 接口请求完后需要关闭loading
    store.commit('main/SPINNING', false);
    return response;
  } else if (code === 800 || code === 801 || code === 802 || code === 803) {
    return response;
  } else {
    return Promise.reject(response.data);
  }
}, error => {
   // 当响应异常时做一些处理
  let message = '';
  // const user = JSON.parse(localStorage.getItem('userInfo'));
  // console.log(user);
  // if (!user) {
  //   setTimeout(() => {
  //     store.commit('main/SHOWMODAL', true);
  //     Message.destroy();
  //   }, 500);
  //   Message.loading({
  //     content: '请先登录'
  //   });
  //   return;
  // }
  if (error && error.response) {
    switch (error.response.status) {
      case 301:
      case 302:
        setTimeout(() => {
          store.commit('main/SHOWMODAL', true);
          Message.destroy();
        }, 500);
        message = '请先登录';
        break;
      case 400: message = '请求错误'; break;
      case 401: message = '请先登录';break;
      case 403: message = '拒绝访问'; break;
      case 404: message = '请求出错'; break;
      case 408: message = '请求超时'; break;
      case 500: message = '服务器错误'; break;
      case 501: message = '服务未实现'; break;
      case 502: message = '网络错误'; break;
      case 503: message = '服务不可用'; break;
      case 504: message = '网络超时'; break;
      case 505: message = 'HTTP版本不受支持'; break;
      case -462: message = '绑定手机号或短信验证成功后，可进行下一步操作哦~'; break;
      default: message = `连接出错(${error.response.status})!`;
    }
  } else {
    message = '连接服务器失败,请检查网络...'
  }
  Message.error({
    content: message,
    duration: 2 * 5
  });
  return Promise.reject(error);
});

export default instance;